<?php
/**
 * Created by PhpStorm.
 * User: gogo
 * Date: 2019/2/22
 * Time: 下午5:22
 */
namespace app\common;

use app\exception\CustomException;
use think\Controller;
use think\Request;

class Common extends Controller
{
    protected $page = 0;
    protected $pageSize = 0;
    protected $userInfo;
    protected $param;

    function __construct(Request $request = null)
    {
        error_reporting(0);
        parent::__construct($request);

        $this->checkParam($request);
        $this->checkPageParam();
    }

    /**
     * 分页参数检验
     *
     * @access private
     */
    private function checkPageParam()
    {
        $this->pageSize = $this->getParam("pageSize");
        $this->page = $this->getParam("page");
        $validateResult = $this->validate([
            "pageSize" => $this->pageSize,
            "page" => $this->page
        ], [
            "pageSize" => 'integer',
            "page" => 'integer'
        ], [
            "pageSize" => "PAGESIZE_ERROR",
            "page" => "PAGE_ERROR"
        ]);

        if (true !== $validateResult) {
            throw new CustomException($validateResult);
        }
        empty($this->pageSize) && $this->pageSize = 20;
    }

    /**
     * 获取客户端传参并校验签名是否正确
     *
     * @access private
     * @param mixed $request Request类
     */
    private function checkParam(Request $request) {
        $this->param = $request->param();
        if(!$this->param['_timestamp'] || !$this->param['sign']){
            exit(fail("DATA_ERROR"));
        }

        $sign = $this->param['sign'];

        $get_param = $request->get();
        if($sign != auth($get_param)){
            exit(fail("SIGN_ERROR"));
        }
    }


    /**
     * 获取参数
     *
     * @access protected
     * @param string $key 参数的名字
     * @param string $default 默认值
     * @return string
     */
    protected function getParam($key = '', $default = '') {
        if (isset($this->param[$key])) {
            if ($this->param[$key] == "") {
                $param = $default;
            } else {
                $param = $this->param[$key];
            }
        } else {
            $param = $default;
        }
        return trim($param);
    }
}